// 崩溃处理, 发邮件提醒管理员注意

package common

import (
	"api/common/logger"
	"fmt"
	"net/smtp"
	"runtime/debug"
	"strings"
	"time"
)

var e_user = "15234579277@139.com"
var e_paswd = "FEVERfever12"
var e_port = "smtp.139.com:25"
var e_host = "smtp.139.com"
var e_port_to = "15234579277@139.com"

//异常日志处理
func PanicHandler() {
	panicContent := ""
	subject := ""
	if err := recover(); err != nil {
		logger.Error(err)
		logger.Error(string(debug.Stack()))
		subject = "[" + time.Now().Format("2006-01-02 15:04:05") + "]后台接口崩溃信息" + fmt.Sprintf("%+v", err)
		panicContent = string(debug.Stack())
	}

	if panicContent != "" {
		SendToMail(e_user, subject, panicContent)
	}
}

//发送邮件
func SendToMail(user, subject, body string) error {
	auth := smtp.PlainAuth("", user, e_paswd, e_host)

	content_type := "Content-Type:text/plain;charset=UTF-8"

	msg := []byte("To: " + user + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
	send_to := strings.Split(user, ";")
	err := smtp.SendMail(e_port, auth, e_port_to, send_to, msg)
	return err
}
